package com.hyh.admin.tool;

import com.jcraft.jsch.*;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class FileUploadService {

    private static final String SFTP_HOST = "1.92.141.215"; // 服务器 IP
    private static final int SFTP_PORT = 22; // 默认 SFTP 端口
    private static final String SFTP_USER = "root"; // 你的服务器用户名
    private static final String SFTP_PASSWORD = "1459hyh."; // 你的服务器密码
    private static final String SFTP_UPLOAD_DIR = "/temp/nginx/html/uploads"; // 服务器存储路径

    public String saveFile(MultipartFile file, String subDir) throws Exception {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 1️⃣ 生成随机文件名
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        String remoteFilePath = SFTP_UPLOAD_DIR + subDir + "/" + fileName;

        // 2️⃣ 连接 SFTP 并上传文件
        uploadToSFTP(file.getInputStream(), remoteFilePath);

        // 3️⃣ 返回可访问的 URL
        return "http://1.92.141.215/uploads" + subDir + "/" + fileName;
    }

    private void uploadToSFTP(InputStream fileStream, String remotePath) throws Exception {
        Session session = null;
        ChannelSftp sftpChannel = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTP_USER, SFTP_HOST, SFTP_PORT);
            session.setPassword(SFTP_PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(); // 连接服务器

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;

            // 确保远程目录存在
            String remoteDir = remotePath.substring(0, remotePath.lastIndexOf('/'));
            try {
                sftpChannel.cd(remoteDir);
            } catch (SftpException e) {
                sftpChannel.mkdir(remoteDir);
                sftpChannel.cd(remoteDir);
            }

            // 上传文件
            sftpChannel.put(fileStream, remotePath);
        } finally {
            if (sftpChannel != null) {
                sftpChannel.exit();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
